package com.example.util;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.example.controller.WebSocketServer;
import com.example.pojo.MessageOuterClass;
import com.google.protobuf.InvalidProtocolBufferException;
import com.microsoft.playwright.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;

public class MsgProcessUtil {

    private static Logger logger = LoggerFactory.getLogger(MsgProcessUtil.class);

    private static String dmUrl = "https://live.douyin.com/webcast/im/fetch/";

    private static String emojiUrl = "https://live.douyin.com/aweme/v1/web/emoji/list";

    private static Map<String,String> emojiMap = new HashMap<>();

    private static Map<Integer,List<String>> content = new HashMap<>();

    private static void initContent(){
        List<String> mans = FileUtil.readLines("classpath:man.txt", "utf-8");
        List<String> woman = FileUtil.readLines("classpath:woman.txt", "utf-8");
        content.put(1,mans);
        content.put(2,woman);
    }

    public static void process(Response response,String id){
        if(CollectionUtil.isEmpty(content)){
            initContent();
        }
        logger.info("url = "+response.url());
        if(response.url().startsWith(dmUrl)){
            try {
                MessageOuterClass.Response response1 = MessageOuterClass.Response.parseFrom(response.body());
                List<MessageOuterClass.Message> messageList = response1.getMessageList();
                Map<String,String> res = new HashMap<>();
                messageList.forEach(message -> {
                    try {
                        if(message.getMethod().equals("WebcastChatMessage")){
                            //评论
                            MessageOuterClass.ChatMessage chatMessage = MessageOuterClass.ChatMessage.parseFrom(message.getPayload());
                            MessageOuterClass.User user = chatMessage.getUser();
                            String img = user.getAvatarThumb().getUrlList(0);

                            String messageContent = chatMessage.getContent();
                            if (messageContent.indexOf("[") >= 0&& messageContent.indexOf("]") >= 0){
                                Set<String> emoji = emojiMap.keySet();
                                messageContent = messageContent.replaceAll("\\[","-").replaceAll("\\]","-");
                                for(String key:emoji){
                                    String val = emojiMap.get(key);
                                    String imgSrc = "<img src=\""+val+"\" style=\"width:35px;height:35px\">";
                                    messageContent = messageContent.replaceAll(key,imgSrc);
                                }
                            }
//                            System.out.println("用户ID=："+user.getId()+"，用户名称："+user.getNickname()+"，说了句："+chatMessage.getContent()+" 用户头像="+img);
                            res.put("img",img);
                            res.put("msg",messageContent);
//                            WebSocketServer.sendInfo(JSONUtil.toJsonStr(res),id);
                        } else if (message.getMethod().equals("WebcastMemberMessage")){
                            //进入直播间
                            MessageOuterClass.MemberMessage memberMessage = MessageOuterClass.MemberMessage.parseFrom(message.getPayload());
                            MessageOuterClass.Common common = memberMessage.getCommon();
                            MessageOuterClass.User userValue = common.getDisplayText().getTextPoece().getUserValue().getUser();
                            String nickname = userValue.getNickname();
                            String img = userValue.getAvatarThumb().getUrlList(0);
//                            System.out.println("进入直播间   用户ID=："+userValue.getId()+"，用户名称："+nickname+" 用户头像="+img);
                            res.put("img",img);
                            List<String> con = content.get(userValue.getGender());
                            if(CollectionUtil.isEmpty(con)){
                                con = content.get(1);
                            }
                            String genderDes = userValue.getGender() == 1?" 小哥哥":userValue.getGender() == 2?" 小姐姐":"";
                            res.put("msg","欢迎 "+nickname+" 祝您:"+con.get(new Random().nextInt(con.size())));
                            WebSocketServer.sendInfo(JSONUtil.toJsonStr(res),id);
                        } else if(message.getMethod().equals("WebcastSocialMessage")){
                            //关注
                            MessageOuterClass.SocialMessage socialMessage = MessageOuterClass.SocialMessage.parseFrom(message.getPayload());
                            MessageOuterClass.User user = socialMessage.getUser();
                            user.getNickname();
//                            System.out.println("关注了主播   用户ID=："+user.getId()+"，用户名称："+user.getNickname()+" 用户头像="+user.getAvatarThumb().getUrlList(0));
                        }else if(message.getMethod().equals("WebcastGiftMessage")){
                            //送礼物
                            MessageOuterClass.GiftMessage giftMessage = MessageOuterClass.GiftMessage.parseFrom(message.getPayload());
                            MessageOuterClass.GiftStruct gift = giftMessage.getGift();
                            MessageOuterClass.User user = giftMessage.getUser();
//                            System.out.println("送出了礼物   用户ID=："+user.getId()+"，用户名称："+user.getNickname()+" 送出了："+gift.getName()+" "+gift.getImage().getUrlList(0)+" "+giftMessage.getGroupCount());

                        }
                    }catch (Exception e){
                        System.out.println(e);
                    }
                });
            } catch (InvalidProtocolBufferException e) {
                e.printStackTrace();
            }
        }else if(response.url().startsWith(emojiUrl)){
            String body = new String(response.body());
            JSONObject jsonObject = JSONUtil.parseObj(body);
            JSONArray emoji_list = jsonObject.getJSONArray("emoji_list");
            emoji_list.forEach(emoji->{
                JSONObject emo = JSONUtil.parseObj(emoji);
                Object emoji_url = emo.get("emoji_url");
                JSONObject urlList = JSONUtil.parseObj(emoji_url);
                Object url_list = urlList.get("url_list");
                JSONArray urls = JSONUtil.parseArray(url_list);
                System.out.println(emo.get("display_name")+","+urls.get(0).toString());
                emojiMap.put(emo.get("display_name").toString().replaceAll("\\[","-").replaceAll("\\]","-"),urls.get(0).toString());
            });
        }
    }
}
